/*
 * Copyright (c) 2011 Ondrej Lapacek
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

/**
 * @author      Ondrej Lapacek
 * @version     1.0, 09/12/11
 * @since       1.0
 */

package cz.muni.fi.android.assistivecamera.intersectiondetector;

import android.graphics.PointF;

public class IntersectionDetectorGeometry {
	
	public PointF findIntersection(PointF start1, PointF end1, PointF start2, PointF end2) { 
		
	    double A1 = end1.y - start1.y; 
	    double B1 = start1.x - end1.x; 
	    double C1 = A1 * start1.x + B1 * start1.y; 
	
	    double A2 = end2.y - start2.y; 
	    double B2 = start2.x - end2.x; 
	    double C2 = A2 * start2.x + B2 * start2.y; 
	
	    double det = (A1 * B2) - (A2 * B1); 
	    
	    PointF returnPoint = new PointF();

	    if (det == 0) {

            // Check if the segments lie on the same line 
            if ((A1 * start2.x) + (B1 * start2.y) == C1) { 
                    if ((Math.min(start1.x, end1.x) < start2.x) && (Math.max(start1.x, end1.x) > start2.x)) 
                            return null; 

                    if ((Math.min(start1.x, end1.x) < end2.x) && (Math.max(start1.x, end1.x) > end2.x)) 
                            return null; 

                    // They are on the same line
                    return null; 
            } 

            // Parallel 
            return null; 
    	} else { 
            double x = (B2 * C1 - B1 * C2) / det; 
            double y = (A1 * C2 - A2 * C1) / det; 

            if ((x > Math.min(start1.x, end1.x) && x < Math.max(start1.x, end1.x)) && 
            		(y > Math.min(start1.y, end1.y) && y < Math.max(start1.y, end1.y))) { 
                    if ((x > Math.min(start2.x, end2.x) && x < Math.max(start2.x, end2.x)) && 
                    		(y > Math.min(start2.y, end2.y) && y < Math.max(start2.y, end2.y))) { 
                    	returnPoint.x = (float) (x);
                    	returnPoint.y = (float) (y);
                        return returnPoint; 
                    } 
            } 

            return null; 
    	} 
	}
	
	public double pointDistance(PointF start1, PointF end1) {
		double dist = Math.sqrt( Math.pow(start1.x-end1.x, 2) + Math.pow(start1.y-end1.y, 2) );
		
		return dist;
	}
}